
<%@ page import="com.asisto.model.Servicio" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <meta name="layout" content="main" />
        <title>Peticion</title>

        <g:javascript src="jquery/jquery-ui-i18n.js"/>

        <g:javascript>

var rmDateStr = '&nbsp;<span class="mmSpanLink" onclick="rmDate(this);">X</span>';
var rmTimeStr = '&nbsp;<span class="mmSpanLink" onclick="rmTimeSlot(this);">X</span>';
var timeSlotStr = '<div class="tslot">Hora comienzo: <input type="text" size="5" name="evStartTime"/> Hora fin: ' +
'<input type="text" size="5" name="evEndTime"/>' + rmTimeStr + '</div>';

            function creaDatePicker(id) {
              var fecha = ${formatDate(format:'dd/MM/yyyy', date:new Date())};
              jQuery.datepicker.setDefaults(jQuery.extend({showMonthAfterYear: false}));
              jQuery(id).datepicker(
                { //showOn: 'button',
                 inline:true,
                  buttonImage: "${resource(dir:'images',file:'date.png')}",
                  buttonImageOnly: true,
                  onSelect: function(dateText, inst) {

                  var dup = false;
                  jQuery('#jornadas input:hidden').each(function(i,n) {
                      if (dateText == $(n).val()) dup = true;
                  });

                  if (dup) return;

                    var contenido = getDateContentStr(dateText,1);
                    jQuery('#jornadas').append(contenido);
                    
                  }


                }
              );

              $(id).datepicker('option', $.extend({showMonthAfterYear: false},
                $.datepicker.regional['es']));

              jQuery(id).datepicker('setDate',fecha);
            }


            function getDateContentStr(dateText, timeSlotCount) {
                var content = '<li class="dtLiBorder"><input type="hidden" name="evDate" value="' + dateText + '"/><span><b>' + dateText + '</b></span>' + rmDateStr;
                for (var i = 0; i < timeSlotCount; i++)
                  content += timeSlotStr;
                content += '<div><span class="addSlot mmSpanLink mmsmall" onclick="addTimeSlot(this);">Añadir otras horas</span></div></li>';
                return content;
            }

           function addTimeSlot(elem) {
                var count = jQuery(elem).parent().parent().find('.tslot').size();
                if (count < 5)
                  jQuery(elem).parent().before(timeSlotStr);
                if (count == 4) jQuery(elem).hide();
           }

           function rmTimeSlot(elem) {
             jQuery(elem).parent().parent().find('.addSlot').show();
             jQuery(elem).parent().remove();
           }
           function rmDate(elem) {
             jQuery(elem).parent().remove();
             if (jQuery('#evDateTime li').size() == 0) {
               jQuery('#evDateTimeDiv').hide();
               jQuery('#finishBtnDiv').hide();
             }
           }

        </g:javascript>

        <script type="text/javascript">

          function isValidTime(valor) {
            return true;
          }
      function saveEventTime() {
        var map = {};
        var optCount = 0;
        var valid = true;
        var validTime = true;

        var cadena = "";
        $('#jornadas li').each(function(i,n) {
          if (valid && validTime) {
            var tmpCount = optCount;
            var date = $(n).find('input:hidden').val();

            //cadena += "[";

            var stTimeArr = $(n).find('input[name="evStartTime"]');
            var i = 0;
            while (i < $(stTimeArr).size() && valid && validTime) {
              var m = $(stTimeArr)[i];
              if ($(m).val() != '') {

                if(!isValidTime($(m).val())) {
                  alert('Please enter time in the format: HH:MM AM/PM');
                  validTime = false;
                }

                else {
                  map['date_' + optCount] = date;
                  cadena += date + ":";
                  
                  map['stTime_' + optCount] = $(m).val();

                  cadena += $(m).val();
                  var tmp = $(m).next('input');
                  if ($(tmp).val() != '') {
                    if(!isValidTime($(tmp).val())) {
                      alert('Please enter time in the format: HH:MM AM/PM');
                      validTime = false;
                    }

                    cadena += "-" +  $(tmp).val();
                    
                    map['enTime_' + optCount] = $(tmp).val();
                  }
                  else {
                    alert('Event end time cannot be empty if there is a start time.');
                    valid = false;
                    return false;
                  }

                  cadena +=",";
                  optCount++;
                }
              }
              i++;
            } // fin while

            cadena += ";";
            if (tmpCount == optCount) {
              // just date, no start/end time
              map['date_' + optCount] = date;
              optCount++;
            }
          }
        }); // fin function que recorre todos los li

        if (!valid || !validTime) return;
        map.optCount = optCount;
        
        submitEventPoll(cadena);

      }


      function submitEventPoll(cadena) {

      

      //obtiene execution
      var exc = jQuery('#executionId').val();

      //map._eventId_finished = 'Finalizar';
      //map.execution = exc;

alert("cadena : " + cadena);

var url = "${createLink(controller:'servicio'
                                              ,action:'perticion'
                                              ,params:['proyecto.id': 'Unaid '])}";

                                                  


        /*jQuery.post('/asisto/admin/servicio/peticion?execution=' + exc, map
        , function(data) {
          if (data.indexOf('success') >= 0) {
              alert('success!');

          }
        });*/


        jQuery("#cadenaFechas").val(cadena);

        jQuery('#_eventId_finished').click();


      }
        </script>

    </head>
    <body>
        <div class="body">
            
            <g:if test="${flash.message}">
            <div class="message">${flash.message}</div>
            </g:if>

            <g:form action="peticion">
                <div class="dialog">

                  <div class="formulario">
                    <div class="titulo">Selección jornadas</div>

                      <div class="campo">
                          <div class="etiqueta">Fecha: </div>
                          <div class="valor">
                              <input type="text" name="fecha" id="fechaJornada" class="datepicker" value="xxx" />
                          </div>
                      </div>

                    <div id="datePicker" style="float:left;"></div>

                    <div id="jornadas" style="float:left;">
                      <ul id="horas"></ul>
                    </div>

                    

                  </div>


                </div>
                <div class="buttons">
                  <input type="hidden" id="cadenaFechas" name="fechas"/>
                    <span class="button"><g:submitButton name="finished" value="Finalizar" /></span>
                    <span class="button"><g:submitButton name="cancel" value="Cancelar" /></span>
                </div>
            </g:form>


          <button onclick="saveEventTime();">Guardar</button>

          

                <jq:jquery>
                    jQuery(function() {
                      creaDatePicker('#datePicker');
                    });
                </jq:jquery>


        </div>
    </body>
</html>
